package icu.groot.alan.servlet.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.groot.alan.entity.TokenEntity;
import icu.groot.alan.service.impl.UserServiceImpl;
import icu.groot.alan.util.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/_update.do")
public class User_UpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        ObjectMapper objectMapper = new ObjectMapper();
        if (code == null || code.equals("")){
            resp.getWriter().print(objectMapper.writeValueAsString(R.error("缺少参数,请联系管理员")));
            return;
        }
        TokenEntity tokenEntity = (TokenEntity) req.getAttribute("tokenEntity");
        String codeInToken = tokenEntity.getCode();
        if (!codeInToken.equals(code) && !tokenEntity.getDepartment().equals("管理员") || code.equals("10000001")){
            resp.getWriter().print(objectMapper.writeValueAsString(R.error("权限不够")));
            return;
        }
        resp.getWriter().print(objectMapper.writeValueAsString(new UserServiceImpl().getUserById(code)));


    }
}
